﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ServerASISTSYS
{
    class FilterManager
    {
        private string          filterPath = null;
        private Filter          rootFilter = null;
        private ServerFunctions sf         = null;

        public FilterManager(ServerFunctions sf)
        {
            filterPath = ServerConfig.GetInstance().GetFilterPath();
            this.sf = sf;
        }

        /// <summary>
        /// Scan & load all filter DLLs
        /// </summary>
        public void ScanAndLoad()
        {
            DirectoryInfo di = new DirectoryInfo(filterPath);
            FileInfo[] filterDLLs = di.GetFiles("*.dll");
            Filter f;
            string dllName;

            rootFilter = f = null;
            foreach (FileInfo dll in filterDLLs)
            {
                dllName = dll.Name.Substring(0, dll.Name.LastIndexOf('.'));
                if (rootFilter == null)
                {
                    rootFilter = f = new Filter(filterPath, dllName);
                    rootFilter.sf = this.sf;
                }
                else
                {
                    Filter tmp = new Filter(filterPath, dllName);
                    tmp.sf = this.sf;
                    f = f.SetNext(tmp);
                }
            }
        }

        /// <summary>
        /// Process a message using the appropiate filter
        /// Trows: UnknownMessageID
        /// </summary>
        /// <param name="length">message length</param>
        /// <param name="ID"    >message ID</param>
        /// <param name="data"  >message data</param>
        public void ProcessMessage(int length, int ID, byte[] data)
        {
            if (rootFilter != null)
                rootFilter.ProcessMessage(length, ID, data);
        }
    }
}
